package com.molyfun.parents.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Menu;

import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.R;
import com.molyfun.parents.activity.account.LoginActivity;
import com.molyfun.parents.activity.common.BaseActivity;
import com.molyfun.parents.push.PushMsgCacheCenter;
import com.molyfun.parents.rest.bean.UserResponse;
import com.molyfun.parents.utils.GsonUtil;
import com.molyfun.parents.utils.NetWorkUtil;
import com.molyfun.parents.utils.PreferencesStorageUtil;

import cn.smssdk.SMSSDK;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class SplashActivity extends BaseActivity {

    Intent intent;
    long waitSeconds = 1200L;

//    private CourseDownloadTaskDao courseDownloadTaskDao;

    public static void startActivity(Context context){
        Intent intent = new Intent();
        intent.setClass(context, SplashActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        getSupportActionBar().setTitle("");

//
//        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(MFPApplication.getInstance(), Const.DB_NAME, null);
//        DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());
//        DaoSession daoSession = daoMaster.newSession();
//        courseDownloadTaskDao = daoSession.getCourseDownloadTaskDao();
//
//        List<CourseDownloadTask> courseDownloadList = courseDownloadTaskDao.queryBuilder()
//                .build().list();
//        for(CourseDownloadTask courseDownloadTask : courseDownloadList){
//            if(courseDownloadTask != null){
//                CourseDownloadProgressCenter.getInstance().addFinishedDownloadCourse(courseDownloadTask.getDownloadKeyId());
//            }
//        }

        SMSSDK.initSDK(this, "1a284daaae0e7", "11ca872c76403134636b2bf5194420c7");
        PreferencesStorageUtil.setLocalPushLastLogoutTime(this, System.currentTimeMillis());
        if(!NetWorkUtil.isNetworkAvailable(SplashActivity.this)){
            toast(R.string.error_network);
        }

        if (!PreferencesStorageUtil.isNewUser(SplashActivity.this)) {
            if(TextUtils.isEmpty(PreferencesStorageUtil.getToken(SplashActivity.this))){
                intent = new Intent(SplashActivity.this, LoginActivity.class);
            }else{
                intent = new Intent(SplashActivity.this, MainActivity.class);
                getUserInfo();
            }
        }else{
            intent = new Intent(SplashActivity.this, GuideActivity.class);
            getUserInfo();
        }

        Handler mHandler = new Handler();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                startActivity(intent);
                finish();
            }
        }, waitSeconds);

    }

    private void getUserInfo(){
        Call<UserResponse> call = MFPApplication.getInstance().getRestClient().getUserInfo();
        call.enqueue(new Callback<UserResponse>() {
            @Override
            public void onResponse(Call<UserResponse> call, Response<UserResponse> response) {
                if (response.body() != null && response.body().getCode() == 200 && response.body().getData() != null ) {
                    MFPApplication.getInstance().setUser(response.body().getData());
                    PreferencesStorageUtil.setUserBean(SplashActivity.this, GsonUtil.toJson(response.body().getData()));
                    PreferencesStorageUtil.setIMUserName(SplashActivity.this, response.body().getData().getImusername());
                    PreferencesStorageUtil.setIMUserPwd(SplashActivity.this, response.body().getData().getImpassword());
                    PreferencesStorageUtil.setStudentId(SplashActivity.this, response.body().getData().getStudentid());
                    PreferencesStorageUtil.setPhoneNum(SplashActivity.this, response.body().getData().getPhone());
                    PreferencesStorageUtil.setAddress(SplashActivity.this, response.body().getData().getAddress());
                    PreferencesStorageUtil.setEmail(SplashActivity.this, response.body().getData().getEmail());
                    if(TextUtils.isEmpty(response.body().getData().getStudentid())){
                        PreferencesStorageUtil.setUserEnter(SplashActivity.this, false);
                    }else{
                        PreferencesStorageUtil.setUserEnter(SplashActivity.this, true);
                        PreferencesStorageUtil.setOriganOutShowSplash(MFPApplication.getInstance(), false);
                    }
                    PushMsgCacheCenter.getInstance().setmCurrentUnreadCount(response.body().getData().getMessageunreadcount());


                    System.out.println("---PreferencesStorageUtil.getServerMode(MFPApplication.getInstance())---" + PreferencesStorageUtil.getServerMode(MFPApplication.getInstance()));
                    System.out.println("---response.body().getData().getImusername()！---" + response.body().getData().getImusername());
                    System.out.println("---response.body().getData().getImpassword()！---" + response.body().getData().getImpassword());

//                    EMClient.getInstance().logout(false);

//                    LoginHxUtil.getInstance().loginHX(new LoginHxUtil.LoginHxCallback() {
//                        @Override
//                        public void onSuccess() {
//                            System.out.println("---登录聊天服务器成功！---");
//                        }
//
//                        @Override
//                        public void onError(String message) {
//                            System.out.println("---登录聊天服务器失败！------" + message);
//                        }
//                    });

//                    if(!TextUtils.isEmpty(response.body().getData().getImusername()) && !TextUtils.isEmpty(response.body().getData().getImpassword())){
//
//                        String cipherPwd = CipherUtil.shaEncrypt(response.body().getData().getImpassword()).toUpperCase();
//                        System.out.println("---response.body().getData().getImpassword cipher()！---" + cipherPwd);
//                        if(!TextUtils.isEmpty(response.body().getData().getImusername()) && !TextUtils.isEmpty(response.body().getData().getImpassword())){
//                            EMClient.getInstance().login(response.body().getData().getImusername(),
//                                    cipherPwd, new EMCallBack() {//回调
//                                        @Override
//                                        public void onSuccess() {
//                                            EMClient.getInstance().groupManager().loadAllGroups();
//                                            EMClient.getInstance().chatManager().loadAllConversations();
//                                            System.out.println("---登录聊天服务器成功！---");
////                            Log.d("main", "登录聊天服务器成功！");
//                                        }
//
//                                        @Override
//                                        public void onProgress(int progress, String status) {
//
//                                        }
//
//                                        @Override
//                                        public void onError(int code, String message) {
//                                            System.out.println("---登录聊天服务器失败！------" + message);
////                            Log.d("main", "登录聊天服务器失败！");
//                                        }
//                                    });
//                        }
////                        EMClient.getInstance().isConnected()
//                    }

                }
            }

            @Override
            public void onFailure(Call<UserResponse> call, Throwable t) {}
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return false;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }
}
